#ifndef __USERLOGINSECTION1_H__
#define __USERLOGINSECTION1_H__

#include "TcpConnection.h"
#include "Logger.h"
#include "Packet.h"
#include "TLV.h"
#include "YesCrypt.h"
#include "MySQLClient.h"
#include <string.h>

using namespace myNameSpace;

class UserLoginSection1 {
public:
    UserLoginSection1(const Packet &packet, shared_ptr<TcpConnection> pTcpConnection, MySQLClient &mysqlClient): _packet(packet), _pTcpConnection(pTcpConnection), _mysqlClient(mysqlClient) {}

    void process() {
        moqi::LOG_INFO("Thread %u: UserLoginSection1.", pthread_self());
        // 1. 获取用户名
        string userName = _packet._msg;
        // 2.1 若该用户名在数据库中不存在，返回error报文
        TLV response;
        if (!_mysqlClient.isExist("monitor_client", "client_name", userName)) {
            char msg[100] = {0};
            sprintf(msg, "User %s doesn't exists", userName.c_str());
            moqi::LOG_INFO(msg);
            response._type = TASK_LOGIN_SECTION1_RESP_ERROR;
            response._length = strlen(msg);
            strcpy(response._data, msg);
            _pTcpConnection->sendInLoop(response);
            return;
        }
        // 2.2 若该用户存在，从数据库中获取setting返回给客户端
        string setting = _mysqlClient.findData("monitor_client", "client_setting", "client_name", userName);
        if (setting.empty()) {
            const char *msg = "Get setting from database failed.";
            moqi::LOG_ERROR(msg);
            response._type = TASK_LOGIN_SECTION1_RESP_ERROR;
            response._length = strlen(msg);
            strcpy(response._data, msg);
        }
        else {
            response._type = TASK_LOGIN_SECTION1_RESP_OK;
            response._length = setting.size();
            memcpy(response._data, setting.c_str(), response._length);
        }
        _pTcpConnection->sendInLoop(response);
    }

private:
    Packet _packet;
    shared_ptr<TcpConnection> _pTcpConnection;
    MySQLClient &_mysqlClient;
};

#endif
